<template>
  <el-dialog :visible.sync="value" :before-close="cancel" class="china-modal-view">
    <template slot="title">
      佣金链设置
    </template>
    <ModalWrapper :min-width="620">
      <el-form :model="$data" ref="refForm" label-position="top" :rules="refRule">
        <el-form-item label="佣金链模式：" >
          <el-select
            v-model="type"
            placeholder="请选择"
          >
            <el-option
              v-for="item in selectOptionList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="设置佣金链："
          v-if="showCashView"
        >
        <!--:label="isFistLevel ? '当前账户已是1级代理，无需设置佣金链': '设置佣金链：'"   v-if="showCashView"-->
          <el-form-item
            class="china-item-view"
            v-for="(item, index) in cashProxyList"
            :key="index"
          >
            <div class="china-left-view">
              <span class="left-title">{{index + 1}}级代理：</span>
              <div class="name-text">{{ item.name }}</div>
            </div>
            <div class="china-right-view" >
              <span class="left-title">抽佣百分比：</span>
              <el-form-item >
              <el-input-number
                @keyup.enter.native="onSubmitForm('refForm')"
                class="edit-input"
                v-model="item.rate"
                :min="0"
                :precision="0"
                controls-position="right"
              ></el-input-number>
              </el-form-item>
              <div class="ratio-text">%</div>
            </div>
          </el-form-item>
          <el-form-item class="china-item-view">
            <div class="china-left-view">
              <span class="left-title">{{ cashProxyList.length + 1 }}级代理：</span>
              <div>(本级)</div>
            </div>
            <div class="china-right-view">
              <span class="left-title">会员返佣方案：</span>
              <el-select
                placeholder="请选择会员返佣方案"
                v-model="cashRuleId"
              >
                <el-option
                  v-for="item in cashData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-form-item>
        <el-form-item label="设置佣金链：" v-if="showCreditView">
          <div
            class="china-item-view"
          >
            <el-form-item class="china-left-view">
              <span class="left-title">总佣金比例：</span>
            </el-form-item>
            <el-form-item class="china-right-view" prop='rateSum'>
              <span class="left-title">分配百分比：</span>
              <el-input-number
                @keyup.enter.native="onSubmitForm('refForm')"
                class="edit-input"
                v-model="rateSum"
                :min="0"
                :max="100"
                :precision="0"
                controls-position="right"
                @change="onChangeRate"
              ></el-input-number>
              <div class="ratio-text">%</div>
            </el-form-item>
          </div>

          <div
            class="china-item-view"
            v-for="(item, index) in creditProxyList"
          >
            <el-form-item class="china-left-view">
              <span class="left-title">{{index + 1}}级代理：</span>
              <div
                :class="{ 'name-text' :  index + 1 !== level }"
              >
                {{ index + 1 === level ? '(本级)' : item.name }}
              </div>
            </el-form-item>
            <!-- <el-form-item :prop="'tableData.' + $index + '.name'" :rules="rule.name"> -->
            <el-form-item class="china-right-view" >
              <span class="left-title">分配百分比：</span>
              <el-input-number
                @keyup.enter.native="onSubmitForm('refForm')"
                class="edit-input"
                v-model="item.rate"
                :min="0"
                :max="100"
                :precision="0"
                controls-position="right"
                @change="onChangeRate"
              ></el-input-number>
              <div class="ratio-text">%</div>
            </el-form-item>
          </div>
          <el-form-item class="china-item-view total-item-view" :error="totalCheck">
            <div class="china-left-view"></div>
            <div class="china-right-view">
              <span class="left-title">合计：</span>
              <div class="title-text">{{creditTotalRate}}%</div>
            </div>
          </el-form-item>

          <div class="member-view">
            <div class="header-view">最低有效会员数：</div>
            <el-input-number
              @keyup.enter.native="onSubmitForm('refForm')"
              class="edit-input"
              v-model="minEffectMemberNum"
              :min="0"
              :precision="0"
              controls-position="right"
            ></el-input-number>
          </div>
        </el-form-item>

      </el-form>
    </ModalWrapper>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="onSubmitForm('refForm')">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>

// components
import ModalWrapper from '@/components/ModalWrapper';

// mixins
import { form, factory } from '@/build';

// services
import { getAgencyProxyLine, updateAgencyProxyLine, updateAgencyProxyCash } from '@/services/api/agency';
import { getCommissionCaseSelectList } from '@/services/api/commission';

const selectOptionList = [{
  value: 'cashProxyList',
  label: '现金网模式(百分比抽佣)',
}, {
  value: 'creditProxyList',
  label: '信用网模式(差值分配)',
}];

export default {
  name: 'edit-commission-chain-dialog',
  props: ['value', 'id', 'rowData'],
  mixins: [form, factory],
  components: {
    ModalWrapper,
  },
  computed: {
    cashProxyList() {
      return this.tableData[selectOptionList[0].value] || [];
    },
    creditProxyList() {
      return this.tableData[selectOptionList[1].value] || [];
    },
    creditTotalRate() {
      return this.creditProxyList.reduce((total, curr) => (total + (curr.rate || 0)), 0);
    },
    level() {
      return this.tableData.level;
    },
    isFistLevel() {
      return this.tableData.level === 1;
    },
    showCashView() {
      return this.type === this.selectOptionList[0].value;
    },
    showCreditView() {
      // return this.type === this.selectOptionList[1].value && !this.isFistLevel;
      return this.type === this.selectOptionList[1].value;
    },
  },
  data() {
    return {
      refRule: {
        rate: [
          { required: true, message: '比例不能为空', trigger: 'blur' },
        ],
      },
      type: selectOptionList[0].value,
      name: null,
      tableData: {},
      cashData: [],
      cashRuleId: null,
      minEffectMemberNum: null,
      selectOptionList,
      totalCheck: '',
      rateSum: 0,
      superRate: '',
    };
  },
  mounted() {
    this.bindGet(getAgencyProxyLine, 'tableData', {
      sendingData: { uid: this.id },
      format: (data) => {
        const {
          itemList = [],
          cashRuleId,
          commMode = 1,
          minEffectMemberNum = 0,
          rateTotal = 0,
        } = data.commLine || {};
        this.cashRuleId = cashRuleId || this.rowData.cashRule;
        this.minEffectMemberNum = minEffectMemberNum;
        this.rateSum = rateTotal;
        const seleMap = selectOptionList[commMode - 1];
        if (seleMap) {
          this.type = seleMap.value;
        }
        if (!itemList.length) return data;
        selectOptionList.forEach((seleItem) => {
          const key = seleItem.value;
          const result = data[key].map((item) => {
            if (item.rate) return item;
            const res = itemList.find(v => v.proxyId === item.uid);
            if (!res) return item;
            return {
              ...item,
              rate: res.rate,
            };
          });
          data = {
            ...data,
            [key]: result,
          };
        });
        return data;
      },
    });
    this.bindGet(getCommissionCaseSelectList, 'cashData', {
      sendingData: { uid: this.id },
    });
    this.getAll();
    this.bindSave(updateAgencyProxyLine, 'saveForm', 'tableData', {
      beforeSend: (data) => {
        const commMode = selectOptionList.findIndex(v => v.value === this.type);
        let commLine = [];
        if ((commMode + 1) == 2) {
          commLine = this.isFistLevel ? (this.tableData.commLine.itemList.length ? data[this.type] : data.creditProxyList) : data[this.type];
        } else if ((commMode + 1) == 1) {
          commLine = this.isFistLevel ? this.tableData.commLine : data[this.type];
        }


        const rateSum = this.type === 'creditProxyList' ? { rateTotal: this.rateSum } : {};
        return {
          commLine: commLine || [],
          uid: this.id,
          cashRuleId: this.cashRuleId,
          // commMode: this.isFistLevel ? 1 : commMode + 1,
          commMode: commMode + 1,
          minEffectMemberNum: this.minEffectMemberNum,
          ...rateSum,
        };
      },
      afterSuccess: () => {
        this.cancel();
        this.$parent.getAll();
      },
    });
  },
  methods: {
    cancel() {
      this.$emit('input', false);
    },
    onChangeRate() {
      // alert(1);
      if (this.rateSum === 0 || _.isUndefined(this.rateSum)) {
        this.totalCheck = '请先输入总比例';
      } else {
        if (this.creditTotalRate > Number(this.rateSum)) {
          this.totalCheck = `合计不能超过${this.rateSum}%`;
          return;
        } if (this.creditTotalRate < Number(this.rateSum)) {
          this.totalCheck = `未分配佣金比例${Number(this.rateSum) - this.creditTotalRate}%`;
          return;
        }
        this.totalCheck = '';
      }
    },
    onSubmitForm(formName) {
      this.onChangeRate();
      this.$refs[formName].validate((valid) => {
        if (!valid) return;
        if (this.type === 'creditProxyList' && this.creditTotalRate > Number(this.rateSum)) return;
        this.doSave({ action: 'saveForm', form: formName });
        this.cancel();
      });
    },
  },

};
</script>

<style lang="scss">
  .china-modal-view {
    .el-input--mini > input {
      text-align: center;
    }
    .china-item-view {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      :global(.el-form-item__content) {
        flex: 1;
        display: flex;
      }

      &.total-item-view {
        :global(.el-form-item__error) {
          padding-top: 8px;
          padding-left: 70%;
        }
      }


      .china-left-view, .china-right-view {
        display: flex;
        align-items: center;
        flex: 1;

        span.left-title {
          width: 100px;
        }

        .ratio-text {
          margin-left: 10px;
        }

        .name-text {
          color: #409eff;
        }

        .title-text {
          width: 50%;
          border-bottom: 1px solid rgba(0, 0, 0, .6);
          text-align: center;
        }
      }
    }

    .member-view {
      line-height: 28px;
      display: flex;
      align-items: center;
      padding: 10px 0;
      .header-view {
        font-weight: 700 !important;
      }
    }
  }
</style>
